/**
 * Created by JetBrains WebStorm.
 * User: Glenn
 * Date: 21-12-11
 * Time: 15:32
 * To change this template use File | Settings | File Templates.
 */

var JSONURL = 'http://mumesint.appspot.com';
//var JSONURL = 'http://sint.local:8888';
var STUDENTID = 'Student(345)';
var USERNAME = 'CroesGlenn';
var TWITTERPIC = 'http://a3.twimg.com/profile_images/1566793447/34616_1351989804788_1382676537_1341867_4194652_a_bigger.jpg';
var TOTALSCORE = 138;
var COURSES = new Array();
var connectButtonSet = false;
var CURRENTCOURSEID,CURRENTCOURSEHASHTAG,CURRENTCOURSENAME;
var CURRENTQUESTION;
var QUESTIONS = new Array();
var TODOITEMID;
var ITEMS;
var ITEMINDEX;

var init = function(){

    twttr.anywhere(function(T){
        if(!T.isConnected()){
            T("#landing-content").connectButton({
                authComplete: function(user){
                    USERNAME = user.data('screen_name');
                    TWITTERPIC = user.data('profile_image_url');
                    $.getJSON(JSONURL + "/api/entries/student?name=" + USERNAME, function(data){
                        STUDENTID = data.results[0].id;
                        TOTALSCORE = data.results[0].score;
                        $.mobile.changePage("#home");
                    });
                }
            });
        }else{
        	$("#landing-content").html('<h2>Welcome to SiNT</h2><p>We got your login info. </p><p>Please wait while everything is loading.</p><p>This can take a few seconds</p>');
            var user = T.currentUser;
            USERNAME = user.data('screen_name');
            TWITTERPIC = user.data('profile_image_url');
            $.getJSON(JSONURL + "/api/entries/student?name=" + USERNAME, function(data){
                STUDENTID = data.results[0].id;
                TOTALSCORE = data.results[0].score;
                $.mobile.changePage("#home");
            });
        }
    });

    $('.homebtn').click(function(event){
        loadHomepage();
    });

    $(".coursebtn").click(function(event){
        loadCourses();
    });

    $('#coursepage').live( 'pagecreate',function(event){
        loadCoursePage();
    });

    $('#score').click(function(event){
       loadGlobalLeaderboard();
    });

    $('#coursescore').click(function(event){
        loadCourseLeaderboard();
    });

    $('#questionsbtn').click(function(){
        loadQuestions();
    });

    $('#questionform').submit(function(){
        $.post('/addquestion',$("#questionform").serialize(), function(data) {
            $.mobile.changePage("#coursepage");
        });
        return false;
    });

    $('#answerform').submit(function(){
        $.post('/addanswer',$("#answerform").serialize(), function(data) {
            $.mobile.changePage("#questionpage");
            loadQuestionpage();
        });
        return false;
    });

    $('#todoform').submit(function(){
    	var deadline = $('#deadline_date').val() + ' ' + $('#deadline_time').val();
        $.post('/addtodo',{'deadline': deadline, 'studentid' : STUDENTID, 'itemid' : $('#itemidinput_todo').attr('value'), 'description': $('#description_body').attr('value')}, function(data) {
        	console.log('todoform submit successfull.')
            $.mobile.changePage("#todo");
            loadTodolist();
        });
        return false;
    });

    $('.todobtn').click(function(){
       console.log('clicked todobtn');
       loadTodolist();
    });
    
    $('#addcoursebtn').click(function(){
    	console.log('clicked addcoursebtn');
    	loadAllCoursesList();
    });
    

    $('#tweetbtn').click(function(){
        $('#tweethere').html("");
        twttr.anywhere(function(T){
           T('#tweethere').tweetBox({
               counter:true,
               height: 150,
               width: 400,
               label: 'Tweet about this course:',
               defaultContent: '#'+CURRENTCOURSEHASHTAG,
               onTweet: function(text, html){
                    $.mobile.changePage('#coursepage');
               }
           });
        });
    });
     $('.logbtn').click(function(){
         twttr.anywhere.signOut();
         $("#landing-content").html('<h2>Welcome to SiNT</h2><p>It looks like you\'re not logged in yet. </p><p>Press the "connect with Twitter"-button to log in using your Twitter account.</p>');
         twttr.anywhere(function(T){
        	 T("#landing-content").connectButton({
        		 authComplete: function(user){
        			 $("#landing-content").html('<h2>Welcome to SiNT</h2><p>We got your login info. </p><p>Please wait while everything is loading.</p><p>This can take a few seconds.</p>');
                     USERNAME = user.data('screen_name');
                     TWITTERPIC = user.data('profile_image_url');
                     $.getJSON(JSONURL + "/api/entries/student?name=" + USERNAME, function(data){
                         STUDENTID = data.results[0].id;
                         TOTALSCORE = data.results[0].score;
                         $.mobile.changePage("#home");
                     });
                 }
        	 });
         }); 
     });
}

var loadHomepage = function(){
	console.log('loading homepage.');
    $('#username').text(USERNAME);
    $('#score').text(TOTALSCORE);
    $('#userpic').attr("src", TWITTERPIC);
    loadStream("/api/entries/stream?studentid=" + STUDENTID + "&size=15", '#home-stream');
    $.mobile.changePage("#home");
}

var loadCourses = function(){
    loadCoursesList();
}

var loadCoursePage = function(){
	console.log('loading course page');
    $('#headertitle').text('SiNT - ' + USERNAME);
    $('#coursename').text(CURRENTCOURSENAME);
    loadStream("/api/entries/stream?studentid=" + STUDENTID
        + "&courseid=" + CURRENTCOURSEID, '#course-stream');
    $.getJSON(JSONURL + "/api/entries/enrollment?studentid=" + STUDENTID + "&courseid=" + CURRENTCOURSEID,
        function(data){
            $('#coursescore').text(data.results[0].score);
        });
    $.mobile.changePage("#coursepage");
}
var calculateNewHtml = function(type, guid, link, author, text, datestamp) {
    var htm = '';
    htm += '<li id="'
        + guid
        + '"><a href= "'
        + link
        + '" rel="external"><img src = "img/' + type + '.png" heigt="50" width="50"></img><h3>'
        + author
        + '</h3><p><strong> '
        + text
        + '</strong></p><p class="ui-li-aside"><strong>'
        + datestamp.substring(0, datestamp.length - 5)
        + '</strong>PM</p></a><a href="#addtodo" data-rel="dialog" data-icon="plus">Add todo</a></li>';
    return htm;
}

var calculateCourseHtml = function(id, link, name, tag) {
    var htm = '';
    htm += '<li id=' + id + '>'
        + '<a href= "'
        + link
        + '"><h3>'
        + name
        + '</h3><p><strong> '
        + tag
        + '</strong></p><p class="ui-li-aside">'
        + '</p></a></li>';
    return htm;
}

var loadStream = function(urlsuffix, list_id) {
	console.log('loading stream ' + urlsuffix);
    ITEMS = new Array();
    $(list_id).html("");
    $.getJSON(JSONURL + urlsuffix, function (data){
        var htm = '';
        var nbItems = data.total_results - 1;				//aantal items in json file
        var results = [ nbItems ];
        $.each(data.results, function(i, result) {
            results[i] = result;						//vul de results-array met json-objecten
        });
        if(data.total_results < 1)
            htm += '<li style="text-align:center;"><h1> NO ITEMS IN STREAM.</h1></li>';
        $.each(results, function(i, result) {
          	if(result == -1)
        		return false;
            var splits = result.id.split("(");
            var type = splits[0];
            if(type == 'Tweet')
                htm += calculateNewHtml('twitter', result.id, result.link, '@' + result.author, result.text, result.datestamp);
//			else if(type == 'Comment')
//				htm += calculateNewHtml('blog', result.guid, result.link, result.author, result.text, result.datestamp);
            else if(type == 'Blog')
                htm += calculateNewHtml('blog', result.id, result.link, result.author, result.text, result.datestamp);
            else if(type == 'Question')
                htm += calculateNewHtml('question', result.id, "", '@' + result.student[0].name, result.question, result.datestamp);
            else if(type == 'Course'){
                htm += calculateCourseHtml(result.id,"", result.name, result.hashtag);
            }
            ITEMS.push(result);
        });
        $(list_id).append(htm);
        $(list_id).listview('refresh');
        $('#studentidinput_todo').attr('value', STUDENTID);
        $(list_id).delegate('li', 'click', function () {
            ITEMINDEX = $(this).index();
            $('#itemidinput_todo').attr('value', ITEMS[ITEMINDEX].id);
            console.log('clicked on item index ' + ITEMINDEX);
        });
    });
}

var loadCoursesList = function(){
	console.log('loading list of courses.');
    $.getJSON(JSONURL + "/api/entries/enrollment/coursesofstudent?studentid=" + STUDENTID, function (data){
        var htm = '';
        var nbItems = data.total_results - 1;				//aantal items in json file
        var results = [ nbItems ];
        if(data.total_results < 1){
        	htm += '<li><h1 style="text-align:center;"> Not enrolled for any courses. Click the "Add course" button above to add courses.</h1></li>';
        	return htm;
        } 
        $.each(data.results, function(i, result) {
            results[i] = result;						//vul de results-array met json-objecten
        });
        $.each(results, function(i, result) {
          	if(result == -1)
        		return false;
            var splits = result.id.split("(");
            var type = splits[0];
            if(type == 'Course'){
                htm += calculateCourseHtml(result.id,"", result.name, result.hashtag);
            }
        });
        $('#courseslist').append(htm);
        $('#courseslist').listview('refresh');
        $('#courseslist li').click(function(){
            CURRENTCOURSEID = $(this).attr("id");
            CURRENTCOURSENAME = $(this).find('h3').text();
            CURRENTCOURSEHASHTAG = $(this).find('strong').text();
            loadCoursePage();
        });
    });
}

var loadGlobalLeaderboard = function(){
	console.log('loading global leaderboard.');
    $('#leaderboardlist').html("");
    $.getJSON(JSONURL + '/api/entries/student?size=10', function (data){
        var htm = '';
        var nbItems = data.total_results - 1;				//aantal items in json file
        var results = [ nbItems ];
        $.each(data.results, function(i, result) {
            results[i] = result;						//vul de results-array met json-objecten
        });
        $.each(results, function(i, result) {
          	if(result == -1)
        		return false;
           htm += '<li id="globalleaderboard-'
               + i
               + '"><p><strong>'
               + (i+1)
               + ') '
               + result.name
               + '</strong></p><p class="ui-li-aside"><strong>'
               + result.score
               + '</strong></p></li>';
        });
        $('#leaderboardlist').append(htm);
        $('#leaderboardlist').listview('refresh');
        $.mobile.changePage('#leaderboard', {role: 'dialog'});
    });
}

var loadCourseLeaderboard = function(){
	console.log('loading course leaderboard.');
    $('#courseleaderboardlist').html("");
    $.getJSON(JSONURL + '/api/entries/enrollment/studentsofcourse?size=10&courseid=' + CURRENTCOURSEID , function (data){
        var htm = '';
        var nbItems = data.total_results - 1;				//aantal items in json file
        var results = [ nbItems ];
        $.each(data.results, function(i, result) {
            results[i] = result;						//vul de results-array met json-objecten
        });
        $.each(results, function(i, result) {
          	if(result == -1)
        		return false;
            htm += '<li id="courseleaderboard-'
                + i
                + '"><p><strong>'
                + (i+1)
                + ') '
                + result.name
                + '</strong></p><p class="ui-li-aside"><strong>'
                + result.coursescore
                + '</strong></p></li>';
        });
        $('#courseleaderboardlist').append(htm);
        $('#courseleaderboardlist').listview('refresh');
        $.mobile.changePage('#courseleaderboard', {role: 'dialog'});
    });
}

var loadQuestions = function(){
	console.log('Loading question list.');
    $('#questionlist').html("");
    QUESTIONS = new Array();
    $.getJSON(JSONURL + '/api/entries/question/withanswers?courseid=' + CURRENTCOURSEID , function (data){
        var htm = '';
        var nbItems = data.total_results - 1;				//aantal items in json file
        var results = [ nbItems ];
        if(data.total_results < 1){
        	htm += '<li><h1 style="text-align:center;"> No questions found.</h1></li>';
        	return htm;
        } 
        $.each(data.results, function(i, result) {
            results[i] = result;						//vul de results-array met json-objecten
        });
        $.each(results, function(i, result) {
          	if(result == -1)
        		return false;
            htm += '<li id="'
                + result.id
                + '"><a href="#questionpage"><h1><strong>'
                + result.question
                + '</strong></h1><h2>'
                + result.student.name
                +'</h2><p class="ui-li-aside"><strong>'
                + result.datestamp.substring(0, result.datestamp.length - 5)
                + '</strong></p></a><a href="#addtodo" data-rel="dialog" data-icon="plus">Add todo</a></li>';
            QUESTIONS.push(result);
        });
        $('#questionlist').append(htm);
        $('#questionlist').listview('refresh');
        $("#questionlist").delegate('li', 'click', function () {
            QUESTIONINDEX = $(this).index();
            loadQuestionpage();
        });
        $('#studentidinput').attr("value",STUDENTID);
        $('#courseidinput').attr("value",CURRENTCOURSEID);
    });
}

var loadQuestionpage = function(){
	console.log('Loading question page');
    $.mobile.changePage('#questionpage');
    var question = QUESTIONS[QUESTIONINDEX];
    $('#answerlist').html("");
    $('#answerlist').listview();
    $('#questionbody').text(question.question);
    $('#questionauthor').text(question.student.name);
    $('#questioncourse').text(question.course.name);
    var htm='';
    if(question.answers.length < 1){
    	htm += '<li><h1 style="text-align:center;"> No answers yet. Be the first to answer!</h1></li>';
    	return htm;
    } 
            $.each(question.answers, function(i, answer){
                htm += '<li id="'
                    + answer.id
                    + '"><h1><strong>'
                    + answer.answer
                    + '</strong></h1> By:'
                    + answer.student.name
                    +'<p class="ui-li-aside"><strong>'
                    + answer.datestamp.substring(0, answer.datestamp.length - 5)
                    + '</strong></p></li>';
            });
     $('#answerlist').append(htm);
     $('#answerlist').listview('refresh');
     $('#studentidinput_ans').attr("value",STUDENTID);
     $('#questionidinput_ans').attr("value",QUESTIONS[QUESTIONINDEX].id);
}

var loadTodolist = function() {
	console.log('Loading TODO list.');
    $('#todolist').html("");
    $.getJSON(JSONURL + '/api/entries/todo/todolist?studentid=' + STUDENTID, function (data){
        var htm = '';
        var nbItems = data.total_results - 1;				//aantal items in json file
        var results = [ nbItems ];
        $.each(data.results, function(i, result) {
            results[i] = result;						//vul de results-array met json-objecten
        });
        if(data.total_results < 1){
        	htm += '<li><h1 style="text-align:center;"> NO TODO ITEMS.</h1></li>';
        }   
        $.each(results, function(i, result) {
        	if(result == -1)
        		return false;
            var splits = result.id.split("(");
            var type = splits[0];
            if(type == 'Tweet')
                htm += calculateNewTodo('twitter', result.todoid, result.link, result.tododescription, result.text, result.tododeadline);
//			else if(type == 'Comment')
//				htm += calculateNewTodo('blog', result.guid, result.link, result.author, result.text, result.datestamp);
            else if(type == 'Blog')
                htm += calculateNewTodo('blog', result.todoid, result.link, result.tododescription, result.text, result.tododeadline);
            else if(type == 'Question'){
                htm += calculateNewTodo('question', result.todoid, "", '@' + result.student[0].name, result.question, result.tododeadline);
            }

        });
        $('#todolist').append(htm);
        $('#todolist').listview('refresh');
        $("#todolist").delegate('li', 'click', function () {
            var todoid = $(this).attr("id");
            $.post('/removetodo', { 'todoid' : todoid}, function(){
            	console.log('TODO item removed.');
            });
            $(this).hide();
        });
    });
}

var loadAllCoursesList = function(){
	$.getJSON(JSONURL + "/api/entries/course", function (data){
        var htm = '';
        var nbItems = data.total_results - 1;				//aantal items in json file
        var results = [ nbItems ];
        $.each(data.results, function(i, result) {
            results[i] = result;						//vul de results-array met json-objecten
        });
        $.each(results, function(i, result) {
            var splits = result.id.split("(");
            var type = splits[0];
            if(type == 'Course'){
                htm += calculateCourseHtml(result.id,"", result.name, result.hashtag);
            }
        });
        $('#allcourseslist').append(htm);
        $('#allcourseslist').listview('refresh');
        $('#allcourseslist li').click(function(){
            var selectedcourseid = $(this).attr("id");
            $.post('/addenrollment?studentid=' + STUDENTID + '&courseid=' + selectedcourseid, function(){
            	$.mobile.changePage("#courses", {role: 'dialog'});
            	loadCoursesList();
            });
        });
    });
}

var calculateNewTodo = function(type, guid, link, author, text, datestamp, description) {
    var htm = '';
    htm += '<li id="'
        + guid
        + '"><a href= "'
        + link
        + '" rel="external"><img src = "img/' + type + '.png" heigt="50" width="50"></img><h3>'
        + author
        + '</h3><p><strong> '
        + text
        + '</strong></p><p class="ui-li-aside"><strong>'
        + datestamp.substring(0, datestamp.length - 5)
        + '</strong>PM</p></a><a href="" class="removetodo" data-icon="check">Done</a></li>';
    return htm;
}

